/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import me.zhengjie.modules.biz.domain.Sensor;
import me.zhengjie.modules.biz.domain.System;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.modules.system.repository.MenuRepository;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.SystemRepository;
import me.zhengjie.modules.biz.service.SystemService;
import me.zhengjie.modules.biz.service.dto.SystemDto;
import me.zhengjie.modules.biz.service.dto.SystemQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.SystemMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-02-20
**/
@Service
@RequiredArgsConstructor
public class SystemServiceImpl implements SystemService {

    private final SystemRepository systemRepository;
    private final SystemMapper systemMapper;
    private final RoleRepository roleRepository;
    private final MenuRepository menuRepository;
    @Override
    public Map<String,Object> queryAll(SystemQueryCriteria criteria, Pageable pageable){
        Map<String,Object> stringObjectMap = new HashMap<>();
        Set<Role> roleSet = roleRepository.findByUserId(SecurityUtils.getCurrentUserId());
        HashSet<Integer> systemSet = new HashSet();
        ArrayList<Role> roleList = new ArrayList(roleSet);
        for (Role role:roleList) {
            ArrayList<Integer> MenuList = menuRepository.findByRoleId(role.getId());
            ArrayList<Integer> MenuIdList = new ArrayList(MenuList);
            for (Integer menuId: MenuIdList) {
//                systemSet.add(systemRepository.findByMenuId(menuId));
                for (Integer sysId:systemRepository.findByMenuId(menuId)) {
                    systemSet.add(sysId);
                }
            }
        }
        ArrayList<Integer> systemIdList = new ArrayList(systemSet);
        ArrayList<System>  systemArrayList= new ArrayList<>();
        for (Integer sysId:systemIdList) {
            systemArrayList.add(systemRepository.findById(sysId).orElseGet(System::new));
        }
        stringObjectMap.put("content",systemArrayList);
        return stringObjectMap;
    }

    @Override
    public List<SystemDto> queryAll(SystemQueryCriteria criteria){
        return systemMapper.toDto(systemRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public SystemDto findById(Integer id) {
        System system = systemRepository.findById(id).orElseGet(System::new);
        ValidationUtil.isNull(system.getId(),"System","id",id);
        return systemMapper.toDto(system);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SystemDto create(System resources) {
        return systemMapper.toDto(systemRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(System resources) {
        System system = systemRepository.findById(resources.getId()).orElseGet(System::new);
        ValidationUtil.isNull( system.getId(),"System","id",resources.getId());
        system.copy(resources);
        systemRepository.save(system);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            systemRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<SystemDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (SystemDto system : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" name",  system.getName());
            map.put(" createdAt",  system.getCreatedAt());
            map.put(" updated",  system.getUpdated());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}
